<template>
  <el-dialog :title="!dataForm.id ? '会员新增' : '会员修改'" :close-on-click-modal="false" :visible.sync="visible" fullscreen center>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form inline :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="客户姓名" prop="name">
        <el-input v-model="dataForm.name" placeholder="客户姓名" style="width: 180px;">
          <el-button slot="append" @click="chooseCustomer">选择客户</el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="卡类型" prop="cardType">
        <el-select v-model="dataForm.cardType" placeholder="请选择">
          <el-option label="会员卡" :value="1"></el-option>
          <el-option label="非会员" :value="0"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="就诊卡号" prop="customerCard" :rules="dataForm.cardType == '1' ? dataRule.customerCard : [{required: false}]">
        <el-input v-model="dataForm.customerCard">
          <el-button slot="append" @click="getCustomerInfo">获取HIS信息</el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="注册门店" prop="saleDeptId">
        <el-select v-model="dataForm.saleDeptId">
          <el-option v-for="item in deptOptions" :key="item.id" :value="item.id" :label="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-divider>客户基本信息</el-divider>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="dataForm.gender" :disabled="showFlag != ''">
          <el-option label="男" :value="0"></el-option>
          <el-option label="女" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthDay">
        <el-input v-model="dataForm.birthDay" @change="birthDayChange" :disabled="showFlag != ''"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone1">
        <el-input v-model="dataForm.phone1" placeholder="联系电话" style="width: 180px;"></el-input>
      </el-form-item>
      <region-linkage ref="regionLinkage" @getCityData="cityData" :provinceCode="province" :cityCode="city" :areaCode="area"></region-linkage>

      <el-form-item label="详细地址" class="miui-textarea" style="width: 100%;">
        <el-input type="textarea" style="width: 100%;" v-model="dataForm.address"></el-input>
      </el-form-item>

      <el-divider content-position="center">会员扩充信息</el-divider>
      <el-form-item label="身份证" prop="certificateNum">
        <el-input v-model="dataForm.certificateNum" style="width: 180px;"></el-input>
      </el-form-item>
      <el-form-item label="职业" prop="job">
        <el-select v-model="dataForm.job">
          <el-option v-for="item in jobOptions" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="人群分类" prop="classify">
        <el-select v-model="dataForm.classify">
          <el-option v-for="item in classifyOptions" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮编" prop="zipCode">
        <el-input v-model="dataForm.zipCode"></el-input>
      </el-form-item>
      <el-form-item label="QQ号码" prop="qqNum">
        <el-input v-model="dataForm.qqNum"></el-input>
      </el-form-item>
      <el-form-item label="E-Mail" prop="email">
        <el-input v-model="dataForm.email" style="width: 180px;"></el-input>
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-select v-model="dataForm.source">
          <el-option v-for="item in sourceOptions" :key="item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="memo">
        <el-input v-model="dataForm.memo" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保 存</el-button>
    </span>
    <personnel-search v-if="personVisible" ref="personnelSearch" @refreshForm="updateForm"></personnel-search>
  </el-dialog>
</template>

<script>
  import {
    getCustomerObj,
    addCustomerObj,
    putCustomerObj,
    getCustomerInfoByVisit
  } from "@/api/eims/customer";
  import { getDeptInfo } from "@/api/admin/dept";
  import PersonnelSearch from "@/components/business/PersonnelSearch";
  import { mapGetters } from "vuex";
  import {
    checkDate,
    getDateFormat
  } from '@/util/tools'

  //	省市县三级联动
  import RegionLinkage from "@/components/business/RegionLinkage";

  var checkPhone = (rule, value, callback) => {
    let phoneReg = /^1[3456789]\d{9}$/;
    if (!phoneReg.test(value)) {
      callback(new Error('手机号码格式不对，请重新输入'))
    } else {
      callback()
    }
  }

  export default {
    data() {
      return {
        ischeck: false,
        visible: false,
        personVisible: false,
        showFlag: "",
        dataForm: {
          name: "",
          customerCard: "",
          gender: "",
          birthDay: "",
          phone1: "",
          address: "",
          cardType: 1,
          saleDeptId: "",
          certificateType: "1",
          certificateNum: "",
          job: "",
          classify: "",
          zipCode: "",
          qqNum: "",
          email: "",
          source: "",
          memo: ""
        },
        dataRule: {
          cardType: [{
            required: true,
            message: "卡类型不能为空",
            trigger: "blur"
          }],
          customerCard: [{
            required: true,
            message: "客户卡号不能为空",
            trigger: "blur"
          }],
          name: [{
            required: true,
            message: "客户名称不能为空",
            trigger: "blur"
          }],
          gender: [{
            required: true,
            message: "性别不能为空",
            trigger: "blur"
          }],
          phone1: [{
              required: true,
              message: "电话不能为空",
              trigger: "blur"
            },
            {
              validator: checkPhone,
              trigger: 'blur'
            }
          ]
        },
        deptOptions: [],
        city: "",
        province: "",
        area: "",
        classifyOptions: [{
            value: 1,
            label: "学龄前儿童"
          },
          {
            value: 2,
            label: "小学生"
          },
          {
            value: 3,
            label: "初中生"
          },
          {
            value: 4,
            label: "高中生"
          },
          {
            value: 5,
            label: "大学生"
          },
          {
            value: 6,
            label: "青年人"
          },
          {
            value: 7,
            label: "中年人"
          },
          {
            value: 8,
            label: "老年人"
          }
        ],
        jobOptions: [{
            value: 1,
            label: "工人"
          },
          {
            value: 2,
            label: "学生"
          },
          {
            value: 3,
            label: "农民"
          },
          {
            value: 4,
            label: "教师"
          },
          {
            value: 5,
            label: "军人"
          },
          {
            value: 6,
            label: "管理者"
          },
          {
            value: 7,
            label: "工程师"
          },
          {
            value: 8,
            label: "其他"
          }
        ],
        sourceOptions: [{
            value: 1,
            label: "慕名而来"
          },
          {
            value: 2,
            label: "活动吸引"
          },
          {
            value: 3,
            label: "老客户"
          },
          {
            value: 4,
            label: "短信"
          },
          {
            value: 5,
            label: "广告宣传"
          },
          {
            value: 6,
            label: "线上"
          }
        ]
      };
    },
    components: {
      PersonnelSearch,
      RegionLinkage
    },
    computed: {
      ...mapGetters(["userInfo"])
    },
    methods: {
      init(id) {
        this.dataForm.saleDeptId = this.userInfo.lessDeptId;
        this.dataForm.id = id || 0;
        this.visible = true;
        this.getDeptList();
        this.province = ''
        this.city = ''
        this.area = ''

        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.dataForm.id) {
            getCustomerObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data;
                this.city = this.dataForm.cityCode * 1;
                this.province = this.dataForm.provinceCode * 1;
                this.area = this.dataForm.areaCode * 1;
                let data = {
                  province: this.province,
                  city: this.city,
                  area: this.area
                }
                this.$refs.regionLinkage.init(data)
              }else{
                this.$message.error(response.data.msg)
              }
            }).catch(error => {
              this.$message.error('绑定人员不存在，请联系管理员')
            })
          } else {
            let data = {
              province: '',
              city: '',
              area: ''
            }
            this.$refs.regionLinkage.init(data)
          }
        });
      },
      cityData(data) {
        this.dataForm.province = data.provinceRegionName;
        this.dataForm.provinceCode = data.province;
        this.dataForm.city = data.cityRegionName;
        this.dataForm.cityCode = data.city;
        this.dataForm.area = data.areaRegionName;
        this.dataForm.areaCode = data.area;
      },
      chooseCustomer() {
        this.personVisible = true;
        this.$nextTick(() => {
          this.$refs.personnelSearch.init();
        });
      },
      updateForm(data) {
        this.dataForm = data;
        this.$set(this.dataForm, 'phone1', data.telPhone)
        this.showFlag = data.customerId;
        this.$nextTick(() => {
          this.city = this.dataForm.city * 1;
          this.province = this.dataForm.province * 1;
          this.area = this.dataForm.area * 1;
        });
      },
      getCustomerInfo(){
        getCustomerInfoByVisit(this.dataForm.customerCard).then(response => {
          if(response.data.code == '0'){
            if(response.data.data.name){
              this.dataForm.name = response.data.data.name
              this.dataForm.phone1 = response.data.data.phone
              let sex
              if(response.data.data.sex == '男') sex = 0
              if(response.data.data.sex == '女') sex = 1
              this.dataForm.gender = sex
              this.dataForm.birthDay = response.data.data.birthday.substring(0,10)
              this.dataForm.certificateNum = response.data.data.idcard
              this.dataForm.address = response.data.data.address
            }else{
              this.$message.warning(response.data.data.resultMsg)
            }
          }
        })
      },
      //  出生日期改变事件
      birthDayChange() {
        if (!checkDate(this.dataForm.birthDay)) {
          this.dataForm.birthDay = ''
          this.$message.warning('请输入正确的日期格式')
          return false
        } else {
          this.dataForm.birthDay = getDateFormat(new Date(this.dataForm.birthDay))
        }
        this.dataForm = { ...this.dataForm
        }
      },
      // 表单提交
      dataFormSubmit() {
				this.ischeck = true
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            this.dataForm.name = this.dataForm.name.trim()
            if (this.dataForm.id) {
              
              putCustomerObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success("修改成功");
                  this.visible = false;
                  this.$emit("refreshDataList");
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            } else {
              this.dataForm.cardNum = this.dataForm.customerCard
              addCustomerObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success("添加成功");
                  this.visible = false;
                  this.$emit("refreshDataList", response.data.data);
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            }
          }else{
						this.ischeck = false
					}
        });
      },
      getDeptList() {
        getDeptInfo().then(response => {
          if(response.data.code == '0'){
            this.deptOptions = response.data.data;
          }else{
            this.$message.error(response.data.msg)
          }
        })
      }
    }
  };
</script>
